const path = require("path");
const express = require("express");

let app = express();

// 解析 JSON 格式的请求体数据 req.body
app.use(express.json());
// 解析 URL-encoded 格式的请求体数据
app.use(express.urlencoded({ extended: false }));
// 托管静态文件
app.use(express.static(path.join(__dirname, "public"))); // 访问路径 http://localhost:8082/css/app.css

// 初始化orm
const orm = require("orm");
app.use(
  orm.express("mysql://test:123456@localhost:3306/test", {
    define: function (db, modeld, next) {
      next();
    },
  })
);

// 将所有api的响应content-type设置为application/json
// 设置跨域
app.all("/api/*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type,Content-Length,Authorization,Accept,X-Requested-With"
  );
  // 设置服务器支持的所有跨域请求的方法
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // res.setHeader("Content-Type", "applicetion/json;chartset-utf-8");
  next();
});

// 设置路由规则
const apiRoute = require("./routes/apiRoute");
app.use("/api", apiRoute);

app.listen(8082, () => {
  console.log("服务器已启动：8082");
});
